package com.casa.POI.dianping;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.StatelessSession;
import org.hibernate.criterion.Property;

public class FixPhoneExecutor extends Executor {

	private int startIndex;

	@Override
	public void execute() {
		StatelessSession s = SessionManager.getInstance().openStatelessSession();
		while (true) {
			List<Shop> shops = getNextBatchShops(s);
			if (shops.size() == 0)
				break;
			s.beginTransaction();
			for (Shop shop : shops) {
				fix(shop);
				s.update(shop);
				printStatus(shop.getPhone());
			}
			s.getTransaction().commit();
		}
		s.close();
	}

	private void fix(Shop shop) {
		String escaped = StringEscapeUtils.escapeHtml3(shop.getPhone());
		String[] values  = escaped.split("&nbsp;");
		List<String> results = new ArrayList<String>();
		for (String value : values) {
			String result = value.replaceAll("\\D+转", "转").replaceAll("转$", "");
			results.add(result);
		}
		String phone = StringUtils.join(results, ':');
		shop.setPhone(phone);
	}

	@SuppressWarnings("unchecked")
	private List<Shop> getNextBatchShops(StatelessSession s) {
		Criteria c = s.createCriteria(Shop.class);
		c.add(Property.forName("phone").isNotNull());
		c.setFirstResult(startIndex);
		c.setMaxResults(ConfigurationManager.getInstance().getBatchSize());
		List<Shop> shops = c.list();
		startIndex += shops.size();
		return shops;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		new FixPhoneExecutor().execute();
	}

}
